// 初始化第二个 MongoDB 实例
print('Initializing MongoDB Instance 2...');

// 等待数据库启动
sleep(5000);

// 初始化副本集
try {
  rs.initiate({
    _id: "rs0",
    members: [
      { _id: 0, host: "localhost:27017" }
    ]
  });
  print('Replica set initialized successfully for instance 2');
} catch (error) {
  print('Replica set already initialized or error:', error.message);
}

// 等待副本集选举完成
sleep(3000);

// 创建测试数据库和集合
db = db.getSiblingDB('testdb');

// 创建用户集合
db.createCollection('users');
db.users.createIndex({ "email": 1 }, { unique: true });

// 创建产品集合
db.createCollection('products');
db.products.createIndex({ "sku": 1 }, { unique: true });

// 创建订单集合
db.createCollection('orders');
db.orders.createIndex({ "order_number": 1 }, { unique: true });

// 创建日志集合
db.createCollection('logs');
db.logs.createIndex({ "timestamp": 1 });

// 插入一些测试日志数据
db.logs.insertMany([
  {
    _id: ObjectId(),
    level: "INFO",
    message: "Instance 2 started successfully",
    timestamp: new Date(),
    service: "mongodb-instance-2",
    details: {
      port: 20728,
      version: "6.0"
    }
  },
  {
    _id: ObjectId(),
    level: "INFO",
    message: "Collections created",
    timestamp: new Date(),
    service: "mongodb-instance-2",
    details: {
      collections: ["users", "products", "orders", "logs"]
    }
  }
]);

print('Instance 2 initialization completed!');
print('Created collections: users, products, orders, logs');
print('Database: testdb');
print('Connection: localhost:20728');
print('Note: This instance is ready to receive synced data from instance 1'); 